package com.shanghaionstar.home.service;

import android.content.Context;
import android.os.Build;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.onstar.cn.api.PublicService;
import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.mag.enumtype.CategoryType;
import com.onstar.cn.mag.enumtype.OSType;
import com.onstar.cn.mag.publicService.PreferentialReqEntity;
import com.onstar.cn.mag.publicService.response.PreferentialResEntity;
import com.onstar.cn.preferential.request.MyDiscountReq;
import com.onstar.cn.preferential.response.MyDiscountResp;
import com.shanghaionstar.enumtype.OSTypeEnum;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import rx.Observable;
import rx.functions.Func0;

/**
 * Created by 7828wc on 16/6/29.
 */
public class PreferentialService extends BaseService<List<PreferentialResEntity>> {
    private Context context;

    public PreferentialService(Context context) {
        this.context = context;
    }

    @Override
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public RequestEntity getRequestEntity() {
        return null;
    }

    public MyDiscountReq getDiscountReq(String contentType) {
        MyDiscountReq discountReq = new MyDiscountReq();
        discountReq.setVin(ApplicationUtil.getInstance().getVin());
        discountReq.setContentType(contentType);
        Vehicle vehicle = ApplicationUtil.getInstance().getCurrentVehicle();
        discountReq.setMake(vehicle == null ? "" : vehicle.getMakeDesc());
        discountReq.setModel(vehicle == null ? "" : vehicle.getModelDesc());
        discountReq.setYear(vehicle == null ? "" : vehicle.getYear());
        return discountReq;
    }

    @Override
    public List<PreferentialResEntity> jsonToBean(String json) {
        return new Gson().fromJson( json,new TypeToken<ArrayList<PreferentialResEntity>>(){}.getType());
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.POST)
    public String commandDataJson(CategoryType type) throws OnStarException{
        PublicService publicService = new PublicService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        PreferentialReqEntity entity = new PreferentialReqEntity();
        if (!CommonUtil.isNull(ApplicationUtil.getInstance().getCurrentVehicle())) {
            entity.setVin(ApplicationUtil.getInstance().getCurrentVehicle().getVin());
            entity.setMake(ApplicationUtil.getInstance().getCurrentVehicle().getMake());
            entity.setModel(ApplicationUtil.getInstance().getCurrentVehicle().getModel());
            entity.setYear(ApplicationUtil.getInstance().getCurrentVehicle().getYear());
        }
        entity.setDeviceType("10");
        entity.setDeviceOS(OSTypeEnum.ANDROID.value());
        entity.setLanguagePreference(DeviceUtil.getLanguage().equalsIgnoreCase("en") ? Language.EN.value() : Language.ZH.value());
        entity.setUserID(ApplicationUtil.getInstance().getIdpID());
        entity.setImgType(OSTypeEnum.ANDROID.value());
        entity.setCategory(type.value());
        String versionCode = new DeviceUtil(context).getAppVersionCode()+"";
        entity.setVersionCode(versionCode + "");
        requestEntity = publicService.getBannerMyDiscount(requestEntity, entity);
        requestEntity.setUrl(requestEntity.getUrl());
        requestEntity = HttpInjectUtils.injectHttp(PreferentialService.this.getClass(), "commandDataJson", requestEntity,CategoryType.class);
        return BusinessUtil.getResponse(getDatas(requestEntity), context);
    }
    //    JsonParseUtil.JsonToBean(ResponBannerEntity.class, json)
    public Observable<List<PreferentialResEntity>> commandData(final CategoryType type) {
        return Observable.defer(new Func0<Observable<List<PreferentialResEntity>>>() {
            @Override
            public Observable<List<PreferentialResEntity>> call() {
                try {
                    List<PreferentialResEntity> result = new Gson().fromJson(commandDataJson(type),new TypeToken<List<PreferentialResEntity>>(){}.getType());
                    return Observable.just(result);
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }


//    平台_系统版本号_应用版本号_客户端语言_手机类型
//    平台取值：android/iphone/ipad
//    客户端语言取值：zh-CN/en-US
//    手机类型:android具体手机model等信息，ios具体型号
//    ANDROID_4.0_31_zh-CN_Galaxy/iphone_9.1_7.0.0_en-US_iphone4/ipad_9.1


    public void setupCustomHead(LinkedHashMap<String, Object> coHashMap) {
        if (coHashMap == null)
            coHashMap = new LinkedHashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(OSType.ANDROID_SMALL.value())
                .append("_")
                .append(DeviceUtil.getOSVersion()).append("_")
                .append(new DeviceUtil(context).getAppVersionCode())
                .append("_")
                .append(DeviceUtil.isChineseLanguage() ? "zh-CN" : "en-US")
                .append("_")
                .append(Build.MODEL);
        coHashMap.put("CLIENT-INFO", stringBuilder);
    }


    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.POST)
    public Observable<List<MyDiscountResp>> getMyDiscount(final MyDiscountReq req) {
        return Observable.defer(new Func0<Observable<List<MyDiscountResp>>>() {
            @Override
            public Observable<List<MyDiscountResp>> call() {
                try {
                    PublicService service = new PublicService(Constants.CURRENT_SERVER_URL);
                    RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
                    LinkedHashMap<String, Object> coHashMap = new LinkedHashMap<String, Object>();
                    coHashMap.put(FinalConstants.HTTP_AUTHORIZATION, ApplicationUtil.getInstance().getToken());
                    setupCustomHead(coHashMap);
                    requestEntity.setCustomHeads(coHashMap);
                    requestEntity = service.getMyDiscount(requestEntity, req);
                    requestEntity = HttpInjectUtils.injectHttp(PreferentialService.this.getClass(), "getMyDiscount", requestEntity, MyDiscountReq.class);
                    return Observable.just((List<MyDiscountResp>) new Gson().fromJson( BusinessUtil.getResponse(getDatas(requestEntity), context)
                            ,new TypeToken<ArrayList<MyDiscountResp>>(){}.getType()));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }
}
